package com.comac.ins.isfd.util;

import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.isfd.domain.IsfdAcousticsFluidMaterial;
import com.comac.ins.isfd.domain.IsfdAcousticsIsotropicSolidMaterial;
import com.comac.ins.isfd.domain.IsfdAcousticsPorousMaterial;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * 声学材料文件解析工具类
 */
@Slf4j
@Component
public class AcousticsMaterialFileParserUtil {

    /**
     * 解析材料文件并返回对应的材料对象
     */
    public Object parseMaterialFile(MultipartFile file) {
        try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {

            String line;
            boolean inMaterialBlock = false;
            String materialType = null;
            String materialName = null;

            // 先读取材料类型和名称
            while ((line = reader.readLine()) != null) {
                line = line.trim();

                if (line.startsWith("BEGIN MATERIAL")) {
                    inMaterialBlock = true;
                    continue;
                }

                if (line.startsWith("END MATERIAL")) {
                    break;
                }

                if (!inMaterialBlock) {
                    continue;
                }

                if (line.startsWith("NAME")) {
                    materialName = line.substring(4).trim();
                } else if (line.startsWith("ISOTROPIC_SOLID")) {
                    materialType = "SOLID";
                    break;
                } else if (line.startsWith("FLUID")) {
                    materialType = "FLUID";
                    break;
                } else if (line.startsWith("POROUS")) {
                    materialType = "POROUS";
                    break;
                }
            }

            if (materialType == null) {
                throw new RuntimeException("无法识别材料类型");
            }

            // 根据材料类型调用相应的解析方法
            switch (materialType) {
                case "SOLID":
                    return parseSolidMaterialFile(file);
                case "FLUID":
                    return parseFluidMaterialFile(file);
                case "POROUS":
                    return parsePorousMaterialFile(file);
                default:
                    throw new RuntimeException("不支持的材料类型: " + materialType);
            }

        } catch (Exception e) {
            log.error("解析材料文件失败", e);
            throw new BaseException("解析材料文件失败: " + e.getMessage());
        }
    }

    /**
     * 解析固体材料文件
     */
    public IsfdAcousticsIsotropicSolidMaterial parseSolidMaterialFile(MultipartFile file) {
        IsfdAcousticsIsotropicSolidMaterial material = new IsfdAcousticsIsotropicSolidMaterial();

        try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {

            parseCommonMaterialFields(reader, material);

            String line;
            boolean inMaterialBlock = false;

            while ((line = reader.readLine()) != null) {
                line = line.trim();

                if (line.startsWith("BEGIN MATERIAL")) {
                    inMaterialBlock = true;
                    continue;
                }

                if (line.startsWith("END MATERIAL")) {
                    break;
                }

                if (!inMaterialBlock) {
                    continue;
                }

                // 解析固体材料特有字段
                if (line.startsWith("POISSON_RATIO")) {
                    double[] values = parseComplexValue(line.substring("POISSON_RATIO".length()).trim());
                    material.setPoissonRatioReal(values[0]);
                    material.setPoissonRatioImag(values[1]);
                } else if (line.startsWith("SOLID_DENSITY")) {
                    double[] values = parseComplexValue(line.substring("SOLID_DENSITY".length()).trim());
                    material.setSolidDensityReal(values[0]);
                    material.setSolidDensityImag(values[1]);
                } else if (line.startsWith("YOUNG_MODULUS")) {
                    double[] values = parseComplexValue(line.substring("YOUNG_MODULUS".length()).trim());
                    material.setYoungModulusReal(values[0]);
                    material.setYoungModulusImag(values[1]);
                }
            }

            log.info("成功解析固体材料文件: {}", material.getMaterialName());
            return material;

        } catch (Exception e) {
            log.error("解析固体材料文件失败", e);
            throw new BaseException("解析固体材料文件失败: " + e.getMessage());
        }
    }

    /**
     * 解析流体材料文件
     */
    public IsfdAcousticsFluidMaterial parseFluidMaterialFile(MultipartFile file) {
        IsfdAcousticsFluidMaterial material = new IsfdAcousticsFluidMaterial();

        try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {

            parseCommonMaterialFields(reader, material);

            String line;
            boolean inMaterialBlock = false;

            while ((line = reader.readLine()) != null) {
                line = line.trim();

                if (line.startsWith("BEGIN MATERIAL")) {
                    inMaterialBlock = true;
                    continue;
                }

                if (line.startsWith("END MATERIAL")) {
                    break;
                }

                if (!inMaterialBlock) {
                    continue;
                }

                // 解析流体材料特有字段
                if (line.startsWith("CP")) {
                    material.setCp(parseSingleValue(line.substring(2).trim()));
                } else if (line.startsWith("CV")) {
                    material.setCv(parseSingleValue(line.substring(2).trim()));
                } else if (line.startsWith("FLUID_DENSITY")) {
                    double[] values = parseComplexValue(line.substring("FLUID_DENSITY".length()).trim());
                    material.setFluidDensityReal(values[0]);
                    material.setFluidDensityImag(values[1]);
                } else if (line.startsWith("SOUND_SPEED")) {
                    double[] values = parseComplexValue(line.substring("SOUND_SPEED".length()).trim());
                    material.setSoundSpeedReal(values[0]);
                    material.setSoundSpeedImag(values[1]);
                } else if (line.startsWith("THERMAL_CONDUCTIVITY")) {
                    material.setThermalConductivity(parseSingleValue(line.substring("THERMAL_CONDUCTIVITY".length()).trim()));
                } else if (line.startsWith("VISCOSITY")) {
                    material.setViscosity(parseSingleValue(line.substring("VISCOSITY".length()).trim()));
                }
            }

            log.info("成功解析流体材料文件: {}", material.getMaterialName());
            return material;

        } catch (Exception e) {
            log.error("解析流体材料文件失败", e);
            throw new BaseException("解析流体材料文件失败: " + e.getMessage());
        }
    }

    /**
     * 解析多孔材料文件
     */
    public IsfdAcousticsPorousMaterial parsePorousMaterialFile(MultipartFile file) {
        IsfdAcousticsPorousMaterial material = new IsfdAcousticsPorousMaterial();

        try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {

            parseCommonMaterialFields(reader, material);

            String line;
            boolean inMaterialBlock = false;

            while ((line = reader.readLine()) != null) {
                line = line.trim();

                if (line.startsWith("BEGIN MATERIAL")) {
                    inMaterialBlock = true;
                    continue;
                }

                if (line.startsWith("END MATERIAL")) {
                    break;
                }

                if (!inMaterialBlock) {
                    continue;
                }

                // 解析多孔材料特有字段
                if (line.startsWith("CP")) {
                    material.setCp(parseSingleValue(line.substring(2).trim()));
                } else if (line.startsWith("CV")) {
                    material.setCv(parseSingleValue(line.substring(2).trim()));
                } else if (line.startsWith("FLOW_RESISTIVITY")) {
                    double[] values = parseComplexValue(line.substring("FLOW_RESISTIVITY".length()).trim());
                    material.setFlowResistivityReal(values[0]);
                    material.setFlowResistivityImag(values[1]);
                } else if (line.startsWith("FLUID_DENSITY")) {
                    double[] values = parseComplexValue(line.substring("FLUID_DENSITY".length()).trim());
                    material.setFluidDensityReal(values[0]);
                    material.setFluidDensityImag(values[1]);
                } else if (line.startsWith("POISSON_RATIO")) {
                    double[] values = parseComplexValue(line.substring("POISSON_RATIO".length()).trim());
                    material.setPoissonRatioReal(values[0]);
                    material.setPoissonRatioImag(values[1]);
                } else if (line.startsWith("POROSITY")) {
                    material.setPorosity(parseSingleValue(line.substring("POROSITY".length()).trim()));
                } else if (line.startsWith("SOLID_DENSITY")) {
                    double[] values = parseComplexValue(line.substring("SOLID_DENSITY".length()).trim());
                    material.setSolidDensityReal(values[0]);
                    material.setSolidDensityImag(values[1]);
                } else if (line.startsWith("THERMAL_CONDUCTIVITY")) {
                    material.setThermalConductivity(parseSingleValue(line.substring("THERMAL_CONDUCTIVITY".length()).trim()));
                } else if (line.startsWith("THERMAL_LENGTH")) {
                    material.setThermalLength(parseSingleValue(line.substring("THERMAL_LENGTH".length()).trim()));
                } else if (line.startsWith("TORTUOSITY")) {
                    material.setTortuosity(parseSingleValue(line.substring("TORTUOSITY".length()).trim()));
                } else if (line.startsWith("VISCOSITY")) {
                    material.setViscosity(parseSingleValue(line.substring("VISCOSITY".length()).trim()));
                } else if (line.startsWith("VISCOUS_LENGTH")) {
                    material.setViscousLength(parseSingleValue(line.substring("VISCOUS_LENGTH".length()).trim()));
                } else if (line.startsWith("YOUNG_MODULUS")) {
                    double[] values = parseComplexValue(line.substring("YOUNG_MODULUS".length()).trim());
                    material.setYoungModulusReal(values[0]);
                    material.setYoungModulusImag(values[1]);
                }
            }

            log.info("成功解析多孔材料文件: {}", material.getMaterialName());
            return material;

        } catch (Exception e) {
            log.error("解析多孔材料文件失败", e);
            throw new BaseException("解析多孔材料文件失败: " + e.getMessage());
        }
    }

    /**
     * 解析通用材料字段（名称和单位系统）
     */
    private void parseCommonMaterialFields(BufferedReader reader, Object material) throws Exception {
        String line;
        boolean inMaterialBlock = false;

        reader.mark(1000); // 标记位置，以便重新读取

        while ((line = reader.readLine()) != null) {
            line = line.trim();

            if (line.startsWith("BEGIN MATERIAL")) {
                inMaterialBlock = true;
                continue;
            }

            if (line.startsWith("END MATERIAL")) {
                break;
            }

            if (!inMaterialBlock) {
                continue;
            }

            // 解析材料名称
            if (line.startsWith("NAME")) {
                String materialName = line.substring(4).trim();
                if (material instanceof IsfdAcousticsIsotropicSolidMaterial) {
                    ((IsfdAcousticsIsotropicSolidMaterial) material).setMaterialName(materialName);
                } else if (material instanceof IsfdAcousticsFluidMaterial) {
                    ((IsfdAcousticsFluidMaterial) material).setMaterialName(materialName);
                } else if (material instanceof IsfdAcousticsPorousMaterial) {
                    ((IsfdAcousticsPorousMaterial) material).setMaterialName(materialName);
                }
            }
            // 解析单位系统
            else if (line.startsWith("UNIT_SYSTEM")) {
                String unitSystem = line.substring("UNIT_SYSTEM".length()).trim();
                if (material instanceof IsfdAcousticsIsotropicSolidMaterial) {
                    ((IsfdAcousticsIsotropicSolidMaterial) material).setUnitSystem(unitSystem);
                } else if (material instanceof IsfdAcousticsFluidMaterial) {
                    ((IsfdAcousticsFluidMaterial) material).setUnitSystem(unitSystem);
                } else if (material instanceof IsfdAcousticsPorousMaterial) {
                    ((IsfdAcousticsPorousMaterial) material).setUnitSystem(unitSystem);
                }
            }
        }

        reader.reset(); // 重置到标记位置
    }

    /**
     * 解析复数格式 {实部, 虚部}
     */
    private double[] parseComplexValue(String valueStr) {
        try {
            // 去除花括号
            valueStr = valueStr.replace("{", "").replace("}", "").trim();
            String[] parts = valueStr.split(",");

            double real = Double.parseDouble(parts[0].trim());
            double imag = parts.length > 1 ? Double.parseDouble(parts[1].trim()) : 0.0;

            return new double[]{real, imag};
        } catch (Exception e) {
            log.warn("解析复数格式失败: {}, 使用默认值", valueStr);
            return new double[]{0.0, 0.0};
        }
    }

    /**
     * 解析单值
     */
    private Double parseSingleValue(String valueStr) {
        try {
            return Double.parseDouble(valueStr.trim());
        } catch (Exception e) {
            log.warn("解析单值失败: {}, 使用默认值", valueStr);
            return 0.0;
        }
    }
}
